package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.ServiceUsage;
import com.atlin.project.model.dto.sysStatistics.ServiceUsageQueryRequest;
import com.atlin.project.model.vo.serviceUsage.ServiceUsageVO;
import com.atlin.project.model.vo.sysStatistics.ServiceUsageResponse;
import com.atlin.project.service.ServiceUsageService;
import com.atlin.project.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author atlin
 * @description
 * @createDate 2024/11/24 13:34
 */
@RestController
@RequestMapping("/sysStatistics")
public class SysStatistics {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private ServiceUsageService serviceUsageService;


    /**
     * 统计AI服务
     *
     * @param serviceUsageQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/serviceUsage")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<ServiceUsageResponse> serviceUsage(@RequestBody ServiceUsageQueryRequest serviceUsageQueryRequest,
                                                           HttpServletRequest request) {
        if (serviceUsageQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer top = serviceUsageQueryRequest.getTop();

        // 限制爬虫
        ThrowUtils.throwIf(top > 20, ErrorCode.PARAMS_ERROR);


        ServiceUsageResponse response = new ServiceUsageResponse();
        QueryWrapper<ServiceUsage> wrapper = new QueryWrapper<>();

        /**
         * 统计 totalTokensConsumed totalUseCount
         */
        wrapper.select("SUM(tokensConsumed) AS totalTokensConsumed, SUM(useCount) AS totalUseCount");
        List<Map<String, Object>> result = serviceUsageService.listMaps(wrapper);

        if (!result.isEmpty()) {
            Map<String, Object> map = result.get(0);
            if (map == null) {
                response.setTotalConsumer(0L);
                response.setUseCount(0);
            } else {
                response.setTotalConsumer(Long.valueOf(map.get("totalTokensConsumed").toString()));
                response.setUseCount(Integer.valueOf(map.get("totalUseCount").toString()));
            }
        }

        /**
         * 统计 top
         */
        wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(ServiceUsage::getTokensConsumed).last("limit " + top);
        List<ServiceUsage> list = serviceUsageService.list(wrapper);

        ArrayList<ServiceUsageVO> topList = new ArrayList<>();
        for (ServiceUsage serviceUsage : list) {
            ServiceUsageVO serviceUsageVO = new ServiceUsageVO();
            BeanUtils.copyProperties(serviceUsage, serviceUsageVO);
            serviceUsageVO.setSysUserVO(sysUserService.getUserVO(sysUserService.getById(serviceUsage.getUserId())));
            topList.add(serviceUsageVO);
        }
        response.setTop(topList);
        return ResultUtils.success(response);
    }
}
